package com.tianji.learning.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tianji.api.client.user.UserClient;
import com.tianji.api.dto.user.UserDTO;
import com.tianji.common.domain.dto.PageDTO;
import com.tianji.common.utils.BeanUtils;
import com.tianji.common.utils.CollUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.learning.domain.dto.QuestionFormDTO;
import com.tianji.learning.domain.po.InteractionQuestion;
import com.tianji.learning.domain.po.InteractionReply;
import com.tianji.learning.domain.query.QuestionPageQuery;
import com.tianji.learning.domain.vo.QuestionAdminVO;
import com.tianji.learning.domain.vo.QuestionVO;
import com.tianji.learning.mapper.InteractionQuestionMapper;
import com.tianji.learning.mapper.InteractionReplyMapper;
import com.tianji.learning.service.IInteractionQuestionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 互动提问的问题表 服务实现类
 * </p>
 *
 * @author ikun
 * @since 2024-08-25
 */
@Service
@RequiredArgsConstructor
public class InteractionQuestionServiceImpl extends ServiceImpl<InteractionQuestionMapper, InteractionQuestion> implements IInteractionQuestionService {

    private final InteractionReplyMapper replyMapper;
    private final UserClient userClient;

    @Override
    public void saveQuestion(QuestionFormDTO questionDTO) {
        //获取登录用户
        Long userId = UserContext.getUser();
        //数据转换
        InteractionQuestion question = BeanUtils.toBean(questionDTO, InteractionQuestion.class);
        //补充数据
        question.setUserId(userId);
        //保存问题
        save(question);
    }

    @Override
    public PageDTO<QuestionVO> queryQuestions(QuestionPageQuery query) {
        // 1.参数校验，课程id和小节id不能都为空
        Long courseId = query.getCourseId();
        Long sectionId = query.getSectionId();
        if (courseId == null && sectionId == null) {
            throw new RuntimeException("课程id和小节id不能都为空");
        }
        // 2.分页查询
        Page<InteractionQuestion> page = lambdaQuery()
                .select(InteractionQuestion.class, info -> !info.getProperty().equals("description"))
                .eq(query.getOnlyMine(), InteractionQuestion::getUserId, UserContext.getUser())
                .eq(courseId != null, InteractionQuestion::getCourseId, courseId)
                .eq(sectionId != null, InteractionQuestion::getSectionId, sectionId)
                .eq(InteractionQuestion::getHidden, false)
                .page(query.toMpPageDefaultSortByCreateTimeDesc());
        List<InteractionQuestion> records = page.getRecords();
        if (records.isEmpty()) {
            return PageDTO.empty(page);
        }
        // 3.根据id查询提问者和最近一次回答的信息
        HashSet<Long> userIds = new HashSet<>();
        HashSet<Long> answerIds = new HashSet<>();
        // 3.1.得到问题当中的提问者id和最近一次回答的id
        for (InteractionQuestion q : records) {
            if (!q.getAnonymity()) {
                userIds.add(q.getUserId());
            }
            answerIds.add(q.getLatestAnswerId());
        }

        // 3.2.根据id查询最近一次回答
        answerIds.remove(null);
        HashMap<Long, InteractionReply> replyMap = new HashMap<>(answerIds.size());
        if (!answerIds.isEmpty()) {
            List<InteractionReply> replies = replyMapper.selectBatchIds(answerIds);
            for (InteractionReply answer : replies) {
                replyMap.put(answer.getId(), answer);
                if (!answer.getAnonymity()) {
                    userIds.add(answer.getUserId());
                }
            }
        }
        // 3.3.根据id查询用户信息（提问者）
        userIds.remove(null);
        Map<Long, UserDTO> userMap = new HashMap<>(userIds.size());
        if (CollUtils.isEmpty(userIds)) {
            List<UserDTO> users = userClient.queryUserByIds(userIds);
            userMap = users.stream()
                    .collect(Collectors.toMap(UserDTO::getId, u -> u));

        }
        // 4.封装VO
        List<QuestionVO> VoList = new ArrayList<>(records.size());
        for (InteractionQuestion q : records) {
            QuestionVO vo = BeanUtils.toBean(q, QuestionVO.class);
            VoList.add(vo);
            if (!q.getAnonymity()) {
                UserDTO user = userMap.get(q.getUserId());
                vo.setUserName(user.getName());
                vo.setUserIcon(user.getIcon());
            }
            InteractionReply reply = replyMap.get(q.getLatestAnswerId());
            if (reply != null) {
                vo.setAnswerTimes(reply.getReplyTimes());
                if (!reply.getAnonymity()) {
                    UserDTO user = userMap.get(reply.getUserId());
                    vo.setLatestReplyUser(user.getName());
                }
            }
        }
        return PageDTO.of(page, VoList);
    }

    @Override
    public QuestionVO queryQuestionById(Long id) {
        //根据id查询问题
        InteractionQuestion question = getById(id);
        //数据校验
        if (question == null) {
            throw new RuntimeException("该问题不存在");
        }
        //查询提问者信息
        QuestionVO vo = BeanUtils.copyBean(question, QuestionVO.class);
        if (!question.getAnonymity()) {
            UserDTO user = userClient.queryUserById(question.getUserId());
            vo.setUserName(user.getName());
            vo.setUserIcon(user.getIcon());
        }
        return vo;
    }

    @Override
    public void updateQuestion(Long id, QuestionFormDTO questionDTO) {
        //获取当前登录用户
        Long userId = UserContext.getUser();
        //查询当前问题
        InteractionQuestion q = getById(id);
        if (q == null) {
            throw new RuntimeException("该问题不存在");
        }
        //判断当前用户是否是提问者
        if (!q.getUserId().equals(userId)) {
            throw new RuntimeException("您没有权限修改该问题");
        }
        //更新问题
        InteractionQuestion question = BeanUtils.copyBean(questionDTO, InteractionQuestion.class);
        question.setId(id);
        updateById(question);

    }


}
